package com.hst.web.base.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.hst.core.Page;
import com.hst.core.ServiceContext;
import com.hst.core.dao.IORDao;
import com.hst.core.dao.ISQLDao;
import com.hst.core.json.JsonUtil;
import com.hst.web.auth.po.LoginRequest;
import com.hst.web.auth.po.User;
import com.hst.web.base.entity.TCompanyEmployee;
import com.hst.web.base.service.EmployeeService;
import com.hst.web.base.service.UserRoleService;
import com.hst.web.base.service.VehicleService;
import com.hst.web.base.ui.CompanyEmployee;
import com.hst.web.base.ui.CompanyInfo;
import com.hst.web.base.ui.CompanyUpgrade;
import com.hst.web.base.ui.EmployeeDetail;
import com.hst.web.base.ui.PersoneltransferInfo;
import com.hst.web.sys.ui.EmployeeUpgrade;
import com.hst.web.sys.web.DBSyncController;

@Controller
@RequestMapping("/company")
public class CompanyController {
	static Logger logger = LoggerFactory.getLogger(CompanyController.class);

	@Autowired
	ISQLDao sql;

	@Autowired
	IORDao dao;

	@Autowired
	EmployeeService empService;

	@Autowired
	VehicleService vService;

	@SuppressWarnings({ "unchecked" })
	private Map<String, Object> parseQuerys(String data) throws JsonParseException, JsonMappingException, IOException {
		Map<String, Object> querys = JsonUtil.read(data, Map.class);
		return querys;
	}

	@Value("${import-company-emp-template}")
	private String importEmpTemplate;

	@Value("${import-company-vehicle-template}")
	private String importVehTemplate;

	@SuppressWarnings("unchecked")
	@RequestMapping("/company-info")
	public void companyInfo(@RequestBody(required = false) String data, Model m)
			throws JsonParseException, JsonMappingException, IOException {
		Map<String, Object> params = null;
		if (data != null)
			params = JsonUtil.read(data, Map.class);
		m.addAttribute("company-info", sql.query("company.company-info", params));
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/employee-info")
	public void employeeInfo(@RequestBody(required = false) String data, Model m)
			throws JsonParseException, JsonMappingException, IOException {
		Map<String, Object> params;
		if (data != null)
			params = JsonUtil.read(data, Map.class);
		else
			params = new HashMap<String, Object>();
		UserRoleService.addCompanyEmpParam(params);

		m.addAttribute("employee", sql.query("company.employee-info", params));
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/company-employee")
	public void dictCompanyEmployeeInfo(@RequestBody(required = false) String data, Model m)
			throws JsonParseException, JsonMappingException, IOException {
		Map<String, Object> params;
		if (data != null)
			params = JsonUtil.read(data, Map.class);
		else
			params = new HashMap<String, Object>();
		UserRoleService.addCompanyEmpParam(params);
		m.addAttribute("company-employee", sql.query("company.company-employee", params));
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/employee-no-apply")
	public void employeeNoApply(@RequestBody(required = false) String data, Model m)
			throws JsonParseException, JsonMappingException, IOException {
		Map<String, Object> params;
		if (data != null)
			params = JsonUtil.read(data, Map.class);
		else
			params = new HashMap<String, Object>();
		UserRoleService.addCompanyEmpParam(params);

		m.addAttribute("employee-no-apply", sql.query("company.employee-no-apply", params));
	}

	/**
	 * @param data
	 * @param m
	 * @throws Exception
	 */
	@RequestMapping("/import-employee")
	public void importEmployee(@RequestParam(value = "upload") MultipartFile file,
			@RequestParam(value = "company", required = false) String company, Model m) throws Exception {
		try {
			empService.importCompanyEmployee(file, m, company);
		} catch(Exception e) {
			logger.info("importCompanyEmployee错误:", e);
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("msg", e.toString());
			map.put("code", "0");
			m.addAttribute("error", map);
		}
	}

	@RequestMapping("/import-vehicle")
	public void importVehicle(@RequestParam(value = "upload") MultipartFile file, Model m)
			throws JsonParseException, JsonMappingException, IOException {
		vService.importVehicle(file, m);
	}

	@RequestMapping("/employeeDetail")
	public void employeeDetail(@RequestBody String data, Model m)
			throws JsonParseException, JsonMappingException, IOException {
		EmployeeDetail employeeDetail = null;
		Map<String, Object> params = parseQuerys(data);
		List<EmployeeDetail> employeeDetailList = (List<EmployeeDetail>) sql.query("employee.list-employee-detail", params);
		if (employeeDetailList.size() > 0) {
			employeeDetail = employeeDetailList.get(0);
		}		
		m.addAttribute("employee", JsonUtil.toString(employeeDetail));
	}
	
	@RequestMapping("/companyEmployeeDetail")
	public void companyEmployeeDetail(@RequestBody String data, Model m)
			throws JsonParseException, JsonMappingException, IOException {
		CompanyEmployee companyEmployee = null;
		Map<String, Object> params = parseQuerys(data);
        UserRoleService.addCompanyEmpParam((Map<String, Object>) params);
		List<CompanyEmployee> companyEmployeeList = (List<CompanyEmployee>) sql.query("employee.list-company-employee", params);
		if (companyEmployeeList.size() > 0) {
			companyEmployee = companyEmployeeList.get(0);
		}
//		String employeeCode = (String) params.get("employeeCode");
//		TCompanyEmployee employee = dao.get(TCompanyEmployee.class, employeeCode);
		m.addAttribute("employee", JsonUtil.toString(companyEmployee));
	}
	
	@RequestMapping("/companyEmployeeDetailAll")
	public void companyEmployeeDetailALL(@RequestBody String data, Model m)
			throws JsonParseException, JsonMappingException, IOException {
		CompanyEmployee companyEmployee = null;
		Map<String, Object> params = parseQuerys(data);
		List<CompanyEmployee> companyEmployeeList = (List<CompanyEmployee>) sql.query("employee.list-company-employee-all", params);
		if (companyEmployeeList.size() > 0) {
			companyEmployee = companyEmployeeList.get(0);
		}
		m.addAttribute("employee", JsonUtil.toString(companyEmployee));
	}	
	
	@RequestMapping("/personReceiveBack")
	public void personReceiveBack(@RequestBody String data, Model m) throws JsonParseException, JsonMappingException,
			IOException, IllegalAccessException, InvocationTargetException {
		PersoneltransferInfo person = JsonUtil.read(data, PersoneltransferInfo.class);
		empService.transBack(person, m);
	}

	@RequestMapping("/personReceivePass")
	public void personReceivePass(@RequestBody String data, Model m) throws JsonParseException, JsonMappingException,
			IOException, IllegalAccessException, InvocationTargetException {
		PersoneltransferInfo person = JsonUtil.read(data, PersoneltransferInfo.class);
		empService.transPass(person, m);
	}
	
	@RequestMapping("/personTransApprovePass")
	public void personTransApprovePass(@RequestBody String data, Model m) throws Exception {
		PersoneltransferInfo person = JsonUtil.read(data, PersoneltransferInfo.class);
		empService.TransApprovePass(person, m);
	}

	DateFormat df = new SimpleDateFormat("yyyyMMdd");
	String generatePathName(String path) {
		int i = path.lastIndexOf("/");
		path = path.substring(0, i + 1) + df.format(new Date()) + "/" + path.substring(i + 1);
	
		return path;
	}

	@RequestMapping("/download-employee-template")
	public void downloadTempate(HttpServletResponse res) throws IOException {
		File file = new File(importEmpTemplate);
		try (InputStream bis = new BufferedInputStream(new FileInputStream(file))) {
			try (BufferedOutputStream bos = new BufferedOutputStream(res.getOutputStream())) {
				IOUtils.copy(bis, bos);
			}
		}
	}

	@RequestMapping("/download-vehicle-template")
	public void downloadVehicleTempate(HttpServletResponse res) throws IOException {
		File file = new File(importVehTemplate);
		try (InputStream bis = new BufferedInputStream(new FileInputStream(file))) {
			try (BufferedOutputStream bos = new BufferedOutputStream(res.getOutputStream())) {
				IOUtils.copy(bis, bos);
			}
		}
	}

	@RequestMapping("/companyUpgrade")
	public void companyUpgrade(@RequestBody String data, Model m)
			throws JsonParseException, JsonMappingException, IOException {
		Map<String, Object> params = parseQuerys(data);
		String d1 = (String) params.get("companyInfo");
		CompanyInfo company = JsonUtil.read(d1, CompanyInfo.class);
		String d2 = (String) params.get("user");
		LoginRequest login = JsonUtil.read(d2, LoginRequest.class);
		empService.companyUpgrade(company, login, m);
	}

	@RequestMapping("/listCompanyAdmin")
	public void listCompanyAdmin(@RequestBody String data, Model m)
			throws JsonParseException, JsonMappingException, IOException {
		CompanyUpgrade companyInfo = JsonUtil.read(data, CompanyUpgrade.class);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("companyCode", companyInfo.getCompanyCode());
		m.addAttribute("users", sql.query("company.listCompanyAdmin", map));
	}

	@RequestMapping("/delgrade")
	public void delgrade(@RequestBody String data, Model m)
			throws JsonParseException, JsonMappingException, IOException {
		EmployeeUpgrade upgrade = JsonUtil.read(data, EmployeeUpgrade.class);
		empService.delgrade(upgrade, m);
	}
}
